<?php
namespace api\modules\shop\controllers;

use common\models\Active;
use common\models\ActiveAttr;
use common\models\GoodsAttr;
use common\models\Order;
use common\models\Shop;
use common\service\CommonService;
use common\service\ConstantService;
use common\service\GlobalUrlService;
use common\service\ActiveService;
use common\service\GoodsService;
use common\models\Goods;
use common\service\WechatService;
use common\service\RedisServer;

class ActiveController extends ShopBaseController{

    //数据中心
    public function actionIndex(){
        $start_time = strtotime(date('Y-m-d ') . '00:00:00');
        $end_time = strtotime(date('Y-m-d ') . '23:59:59');
        //需要统计的数据
        //1 日,总订单数
        $order_query = Order::find();
        $max_time = ['>=', 'created_time', $start_time];
        $min_time = ['<=', 'created_time', $end_time];
        $pay_status = ['=', 'pay_status', 1];
        $shop_ids = ['=', 'shop_id', $this->shop['shop_id']];
        $noeq = ['!=', 'order_status', 6];
        $day_order = $order_query->select('count(id) as day_order_count')
            ->andWhere($max_time)
            ->andWhere($min_time)
            ->andWhere($pay_status)
            ->andWhere($shop_ids)
            ->andWhere(['>=', 'order_status', 1])
            ->asArray()
            ->one();
        $count_order = Order::find()->select('count(id) as order_count')
            ->andWhere($pay_status)
            ->andWhere($shop_ids)
            ->andWhere(['>=', 'order_status', 1])
            ->asArray()
            ->one();

        //2. 日,总商品销量 算法: 已完成
        $count_goods = Order::find()->select('sum(goods_num) as goods_count')
            ->andWhere($pay_status)
            ->andWhere($shop_ids)
            ->andWhere($noeq)
            ->asArray()
            ->one();
        //3 日,总销售金额 算法:已完成
        //日销售金额
        $day_money_ywc = $order_query->select('sum(order_money) as day_money_count')
            ->andWhere($max_time)
            ->andWhere($min_time)
            ->andWhere($pay_status)
            ->andWhere($noeq)
            ->andWhere($shop_ids)
            ->asArray()
            ->one();
        //总销售金额
        $count_money_ywc = Order::find()->select('sum(order_money) as money_count')
            ->andWhere($pay_status)
            ->andWhere($noeq)
            ->andWhere($shop_ids)
            ->asArray()
            ->one();
        //4. 退款订单
        $order_status_4 = Order::find()->select('count(id) as count_order')
            ->where(['shop_id'=>$this->shop['shop_id'],'order_status'=>4,'is_delete'=>0])->asArray()->one();
        //5. 待发货订单
        $order_status_1 = Order::find()->select('count(id) as count_order')
            ->where(['shop_id'=>$this->shop['shop_id'],'order_status'=>1])->asArray()->one();
        //店铺logo
        $shop=Shop::find()->where(['id'=>$this->shop['shop_id']])->one();
        $shop_logo=GlobalUrlService::buildCdnUrl($shop['shop_logo']);

        //店铺名称
        $shop_name=$shop['shop_name'];

        $data_center = [
            'day_count' => $day_order['day_order_count'],
            'order_countAll' => $count_order['order_count'],
            'count_goods' => $count_goods['goods_count'],
            'money_totle' =>substr(sprintf("%.3f", $day_money_ywc['day_money_count']),0,-1),//round($day_money_ywc['day_money_count'],2),
            'money_totleAll' =>substr(sprintf("%.3f", $count_money_ywc['money_count']),0,-1),//round($count_money_ywc['money_count'],2),
            'tui_count' =>$order_status_4['count_order'],
            'dai_count' =>$order_status_1['count_order'],
            'shop_logo'=>$shop_logo,
            'shop_name'=>$shop_name
        ];

        return $this->renderJson([$data_center],'数据中心：tui_count退款中订单数，dai_count代发货订单数，day_count日订单数，money_totle日销售总金额,shop_logo店铺logo',ConstantService::$response_success);
    }
    /*
     * 商家活动列表
     * */
    public function actionActive(){
        $name = $this->post('name');
        $ac_query = Active::find();
        $ac_query->andWhere(['is_del'=>0]);
        $ac_query->andWhere(['shop_id'=>$this->shop['shop_id']]);
        if(!empty($name)){
            $ac_query->andWhere(['like','active_name',$name]);
        }
        $p = intval( $this->post('page',1) );
        $p = ( $p > 0 )? $p : 1;
        $offset = ($p - 1) *  $this->page_size;
        $data_end = $ac_query->limit( $this->page_size)->orderBy('create_time desc')->offset($offset)->asArray()->all();
        foreach ($data_end as $value){
            if (intval($value['end_time'])<time()){
                $attr_status = Active::findOne(['id'=>$value['id']]);

                $attr_status['status']=2;
                $attr_status->save();
            }
        }
        return $this->renderJson([$data_end,$name],'',ConstantService::$response_success);
    }

    /*
     * 单个开始活动
     * */
    public function actionBegin(){
        if ($this->isPost()){
            $id = $this->post('id');
            $data = Active::find()->where(['id'=>$id])->one();
            if($data['status'] == 3){
                return $this->renderJson([],'该活动被禁用!',ConstantService::$response_fail);
            }
            if($data['begin_time'] >= time()){
                return $this->renderJson([],'活动未到开始时间!',ConstantService::$response_fail);
            }
            if($data['end_time'] < time()){
                return $this->renderJson([],'活动已结束!',ConstantService::$response_fail);
            }
            $data['status'] = 1;
            $re = $data->save();
            if ($re){
                return $this->renderJson([],'激活成功',ConstantService::$response_success);
            }
        }
        return $this->renderJson([],'激活失败',ConstantService::$response_fail);
    }

    /*
     * 开始全部活动
     * */
    public function actionBeginAll(){
       // if ($this->isPost()){
        $active_model = Active::find();
        $active_model->select('id');
        $active_model->andWhere(['>','end_time',time()]);
        $active_model->andWhere(['status'=>0]);
        $active_model->andWhere(['<=','begin_time',time()]);
        $active_model->andWhere(['shop_id'=>$this->shop['shop_id']]);
        $active_model->asArray();
        $data = $active_model->all();
        if(empty($data)){
            return $this->renderJson([],'没有可以激活的活动',ConstantService::$response_fail);
        }
        $aid = [];
        foreach ($data as $v){
            $aid[] = $v['id'];
        }
        
        Active::updateAll(['status'=>1,'update_time'=>time()],['id'=>$aid]);
        return $this->renderJson([],'所有活动激活成功',ConstantService::$response_success);
    }

    /*
     * 暂定某一个活动
     */
    public function actionEnd(){
        if($this->isPost()){
            $id = $this->post('id');
            $data = Active::find()->where(['id'=>$id])->one();
            $data['status'] = 0;
            $re = $data->save();
            if ($re){
                return $this->renderJson([],'暂停成功',ConstantService::$response_success);
            }else{
                return $this->renderJson([],'暂停失败',ConstantService::$response_fail);
            }
        }
    }

    /*
     *   暂停所有活动
     * */
    public function actionEndAll(){
        $active_model = Active::find();
        $active_model->select('id');
        $active_model->andWhere(['>','end_time',time()]);
        $active_model->andWhere(['<=','begin_time',time()]);
        $active_model->andWhere(['status'=>1]);
        $active_model->andWhere(['shop_id'=>$this->shop['shop_id']]);
        $active_model->asArray();
        $data = $active_model->all();
        if(empty($data)){
            return $this->renderJson([],'没有可以暂停的活动',ConstantService::$response_fail);
        }
        $aid = [];
        foreach ($data as $v){
            $aid[] = $v['id'];
        }
        Active::updateAll(['status'=>0,'update_time'=>time()],['id'=>$aid]);
        return $this->renderJson([],'所有活动暂停成功',ConstantService::$response_success);
    }

    /*
     * 查案活动详情（活动列表页面点击“查看/编辑”）
     * */
    public function actionSelect(){
        if ($this->isPost()){
            $activity_id = $this->post('id');
            $activity = Active::find()->where(['id'=>$activity_id])->one();
            $attr = ActiveService::GetAttrlist($activity_id);
            return $this->renderJson(['activity'=>$activity,'activity_attr'=>$attr],"查看成功",ConstantService::$response_success);
        }
        return $this->renderJson([],'请用正确的方式进入查看页面',ConstantService::$response_fail);
    }

    /**
     * 修改活动属性
     * @return string|void
     */
     public function actionUpdataindex(){
            $data = $this->post();
            $msg = $this->_validate($data);
            if($msg !== true){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }
            $active = Active::find()->where(['id'=>$data['id']])->one();
            $active_attr = json_decode($this->post("active_attr"),true);

            //修改活动检索库存
            $goods_attr_data = GoodsAttr::find()->select(['id','inventory'])->where(['goods_id'=>$active['goods_id']])->asArray()->all();
            $active_attr_data = ActiveAttr::find()->select(['id','goods_attre_id','inventory'])->where(['active_id'=>$data['id']])->asArray()->all();
            foreach ($goods_attr_data as $aad){
                $Newgoods_attr_data[$aad['id']] = $aad;
            }
            foreach ($active_attr_data as $aad){
                $Newactive_attr_data[$aad['goods_attre_id']] = $aad;
            }
            $invent = [];//商品库存
            foreach ($active_attr as $v){
                $inum = $Newgoods_attr_data[$v['goods_attr_id']]['inventory'];
                if(isset($Newactive_attr_data[$v['goods_attr_id']])){
                    $inum += $Newactive_attr_data[$v['goods_attr_id']]['inventory'];
                    unset($Newactive_attr_data[$v['goods_attr_id']]);
                }
                if (trim($inum) <  trim($v['inventory'])){
                    return $this->renderJson([],'活动库存大于商品库存，请修改商品库存',ConstantService::$response_fail);
                } else {
                    $inventdata['inventory'] = $inum-$v['inventory'];
                    $inventdata['id'] = $v['goods_attr_id'];
                    $invent[] = $inventdata;
                }
            }


            $delattrid = []; //删除过的活动库存
            foreach ($Newactive_attr_data as $ins){
                $inventdata['inventory'] = $Newgoods_attr_data[$ins['goods_attre_id']]['inventory']+$ins['inventory'];
                $inventdata['id'] = $ins['goods_attre_id'];
                $invent[] = $inventdata;
                $delattrid[] = $ins['id'];
            }
            $collage_price = array_column($active_attr,'collage_price');
            $data['status'] = 0;
            if(strtotime($data['end_time']) < time()){
                $data['status'] = 2;
            }
            $active->setAttributes([
                'active_name'=> $data['active_name'] ,
                'active_num'=>$data['active_num'] ,
                'max_price' => max($collage_price),
                'min_price' => min($collage_price),
                'begin_time' => strtotime($data['begin_time']),
                'end_time' => strtotime($data['end_time']),
                'status' => $data['status'] ,
            ]);

            $save = $active->save();
            if ($save){
                // 查询数据库中原有的活动属性
                $addattr = [];
                foreach($active_attr as $value){
                    $active_attr_model = ActiveAttr::find()->where(['active_id'=>$data['id'],'goods_attre_id'=>$value['goods_attr_id']])->one();
                    //判断活动是否添加过该属性有就直接改 没有就新增
                    if($active_attr_model){
                        $active_attr_model->attr_img = $value['attr_img'];
                        $active_attr_model->original_price = $value['original_price'];
                        $active_attr_model->collage_price = $value['collage_price'];
                        $active_attr_model->inventory = $value['inventory'];
                        $active_attr_model->is_del = 0;
                        $active_attr_model->update_time = time();
                        $active_attr_model->save(false);
                    } else {
                        $attr['attr_img'] = $value['attr_img'];
                        $attr['collage_price'] = $value['collage_price'];
                        $attr['original_price'] = $value['original_price'];
                        $attr['inventory'] = $value['inventory'];
                        $attr['attribute_value_id'] = $value['activity_attr_id'];
                        $attr['goods_attre_id'] = $value['goods_attr_id'];
                        $attr['active_id'] = $data['id'];
                        $attr['sales_volume'] = 0;
                        $attr['is_del'] = 0;
                        $attr['create_time'] = time();
                        $attr['update_time'] = time();
                        $addattr[] = $attr;
                    }
                }

                //添加活动属性
                if(!empty($addattr)) {
                    ActiveAttr::getDb()->createCommand()->batchInsert('active_attr',
                        ['attr_img', 'collage_price', 'original_price', 'inventory', 'attribute_value_id', 'goods_attre_id', 'active_id', 'sales_volume', 'is_del', 'create_time', 'update_time'],
                        $addattr)->execute();
                }
                //删除未选择的活动属性
                ActiveAttr::updateAll(['is_del'=>1,'inventory'=>0,'update_time'=>time()],['id'=>$delattrid]);
                $this->_modifyInventory($invent);
                return  $this->renderJson([],'修改成功',ConstantService::$response_success);
            }
            return  $this->renderJson([],'修改失败',ConstantService::$response_fail);




    }

    /*
     * 删除活动
     * */
    public function actionDel(){
        if ($this->isPost()){
            $id = $this->post('id');
            $re = Active::findOne($id);
            $re->is_del = 1;
            if ($re->save()){
                ActiveService::DelActive($id);
                return $this->renderJson([],'删除成功',ConstantService::$response_success);
            }
        }
        return $this->renderJson([],'删除失败',ConstantService::$response_fail);
    }



    /*
     * 加载添加活动提交接口
     * */
    public function actionAdd(){
        $activity= new Active();
        if ($this->isPost()){
            $data = $this->post();
            $attrs = json_decode($this->post('active_attr'),true);
            $msg = $this->_validate($this->post());
            if($msg !== true){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }
            //检查商品库存
            $modify_inventory = $this->_GetGoodsAttr($attrs);

            $goodsData = Goods::find()
                ->select('list_img')
                ->where(['id'=>$data['goods_id']])
                ->asArray()
                ->one();

            unset($data['active_attr']);
            $collage_price = array_column($attrs,'collage_price');
            $data['shop_id'] = $this->shop['shop_id'];
            $data['status'] = 0;
            $data['begin_time'] = strtotime($data['begin_time']);
            $data['end_time'] = strtotime($data['end_time']);
            $data['qrcode'] = '';
            $data['is_del'] = 0;
            $data['sales_volume'] = 0;
            $data['display_sales'] = 0;
            $data['type'] = 0;
            $data['set_top'] = 0;
            $data['max_price'] = max($collage_price);
            $data['min_price'] = min($collage_price);
            $data['goods_img'] = $goodsData['list_img'];
            $data['create_time'] = time();
            $data['update_time'] = time();
            $active_model = new Active();
            $active_model->setAttributes($data);
            if($active_model->save()){
                $active_id = \Yii::$app->db->getLastInsertID();
                foreach ($attrs as &$attr){
                    $attr['active_id'] = $active_id;
                    $attr['sales_volume'] = 0;
                    $attr['is_del'] = 0;
                    $attr['create_time'] = time();
                    $attr['update_time'] = time();
                }
                //保存属性值
                $re = ActiveAttr::getDb()->createCommand()->batchInsert('active_attr',
                    ['attr_img','collage_price','original_price','inventory','goods_attre_id','attribute_value_id','active_id','sales_volume','is_del','create_time','update_time'],
                    $attrs)->execute();
                if($re){
                    //减商品库存
                    $this->_modifyInventory($modify_inventory);
                    return $this->renderJson([],'活动添加成功',ConstantService::$response_success);
                }
                return $this->renderJson([],'保存活动属性失败',ConstantService::$response_fail);
            }
        }
        return $this->renderJson([],'活动主表添加失败',ConstantService::$response_fail);
    }
    /**
     * 修改库存
     * @param $data
     * @return bool
     */
    private function _modifyInventory($data){

        if(empty($data)){
            return false;
        }
        $redis = RedisServer::initialization();
        foreach ($data as $val){
            $goods = GoodsAttr::findOne(['id'=>$val['id']]);
            $goods->inventory = $val['inventory'];
            $goods->save();
            $key = ConstantService::$redis_key.$val['id'];

            if($redis->getRedis($key)) {
                $redis->addRedis($key, $val['inventory']);
            }
        }
        return true;
    }

    /**
     * 商品搜索
     */
    public function actionAddSelect(){

        $goods_name = $this->get('goods_name');
        $query = Goods::find();
        $query->andWhere(['is_del'=>0]);
        $query->andWhere(['shop_id'=>$this->shop['shop_id']]);
        if(!empty($goods_name)){
            $query->andWhere(['like','goods_name',$goods_name]);
        }

        $p = intval( $this->get('p',1) );
        $p = ( $p > 0 )? $p : 1;

        $offset = ($p - 1) * $this->page_size;

        $lists = $query
            ->select(['id','goods_name'])
            ->orderBy(['created_at' => SORT_DESC, 'id' => SORT_ASC])
            ->offset( $offset )
            ->limit( $this->page_size )
            ->asArray()
            ->all();
        $data['lists'] = $lists;
        $pages = CommonService::ipagination( [
            'total_count' => $query->count(),//总条数
            'page_size' => $this->page_size,
            'page' => $p,
            'display' => 10
        ]);
        $data['count'] = $pages;
        return $this->renderJson($data,'获取成功',ConstantService::$response_success);
    }
    /**
     * 获取商品SKU
     */
    public function actionGetsku(){
        $goods_id = $this->post('id');
        $aid = $this->post('aid');
        $skuData = GoodsService::GetAttrlist($goods_id,0,$aid);
        $cdn = GlobalUrlService::buildCdnUrl('');
        if ($skuData){
            return $this->renderJson(['goods_attr'=>$skuData,'cdn'=>$cdn],"获取成功",ConstantService::$response_success);
        }
        return $this->renderJson([],'获取失败',ConstantService::$response_fail);
    }

    //活动二维码
    public function actionQrcode(){
        $aid = $this->post('id');
        $active = Active::find()->where(['id'=>$aid])->one();
        if (empty($active['qrcode'])){
            $qrcode = WechatService::getWechatQrcode('?id='.$aid,"pages/detail/detail");
            if($qrcode===false){
                return $this->renderJson([],'获取失败',ConstantService::$response_fail);
            }else{
                $active["qrcode"] = $qrcode;
                $active->save();
                $cdnUrl = GlobalUrlService::buildCdnUrl($qrcode);
                return $this->renderJson(['cdnUrl'=>$cdnUrl],"获取成功",ConstantService::$response_success);
            }
        }else{
            $path = $active["qrcode"];
            $cdnUrl = GlobalUrlService::buildCdnUrl("$path");
            return $this->renderJson(['cdnUrl'=>$cdnUrl],"获取成功",ConstantService::$response_success);
        }
    }

    /**
     * 验证数据
     * @param $data
     * @return bool|string
     */
    private function _validate($data){

        if(empty($data['goods_id'])){
            return '商品id不能为空';
        }

        if(empty($data['active_name'])){
            return '活动名称不能为空';
        } else {
            $active = Active::find();
            $active->andWhere(['active_name'=>$data['active_name']]);
            $active->andWhere(['is_del'=>0]);
            $active->andWhere(['shop_id'=>$this->shop['shop_id']]);
            if(isset($data['id'])){
                $active->andWhere(['!=','id',$data['id']]);
            }
            $activeData = $active->asArray()->one();

            if(!empty($activeData)){
                return "活动名称已存在";
            }
        }
        if(empty($data['active_num'])){
            return '参团人数不能为空';
        }
        if(empty($data['begin_time'])){
            return '开团时间不能为空';
        }

        if(empty($data['end_time'])){
            return '结束时间不能为空';
        }
        if(empty($data['active_attr'])){
            return '活动属性不能为空';
        }
        $begin_time = strtotime($data['begin_time'].'00:00:00');
        $end_time = strtotime($data['end_time'].'23:59:59');
        if($begin_time>$end_time){
            return '开团时间不允许大于结束时间';
        }
        if($data['active_num'] > 10){
            return '参团人数最多10人';
        }
      

        return true;
    }

    /**
     * 添加检查商品库存
     */
    private function _GetGoodsAttr($attrs){
        $goods_attre_ids = array_column($attrs,'goods_attre_id');

        $goods_attrs = GoodsAttr::find()->where(['id'=>$goods_attre_ids])->asArray()->all();
        $new_goods_attr = [];
        foreach ($goods_attrs as $val){
            $new_goods_attr[$val['id']] = $val;
        }
        $modify_inventory = []; //需要修改的库存和id
        $errors = '';
        //判断库存
        foreach ($attrs as $attr){
            if($attr['inventory'] < 1){
                $errors .= '拼团价为'.$attr['collage_price'] .'的商品库存不能为0!';
                continue;
            }
            if(isset($new_goods_attr[$attr['goods_attre_id']] ) && !empty($new_goods_attr[$attr['goods_attre_id']])){
                if($new_goods_attr[$attr['goods_attre_id']]['inventory'] < $attr['inventory']){
                    $errors .= '拼团价为'.$attr['collage_price'] .'的商品库存小于活动库存!';
                    continue;
                }else{
                    $arr['id'] = $attr['goods_attre_id'];
                    $arr['inventory'] = $new_goods_attr[$attr['goods_attre_id']]['inventory'] - $attr['inventory'];
                    array_push($modify_inventory,$arr);
                }
            }
        }
        if(!empty($errors)){
            return $this->renderJson([],$errors,ConstantService::$response_fail);
        }
        return $modify_inventory;
    }
}